package demo1;

import java.util.*;

public class Text {
    public List<String> topKFrequent(String[] words, int k) {
        List<String> list = new ArrayList<>();
        Map<String, Integer> map = new HashMap<>();
        for(int i = 0; i < words.length; i++)
            map.put(words[i], map.getOrDefault(words[i], 0) + 1);
        PriorityQueue<String> queue = new PriorityQueue<>((a, b) -> {
            int f1 = map.get(a);
            int f2 = map.get(b);
            if(f1 == f2) {
                return a.compareTo(b);
            }else {
                return f2 - f1;
            }
        });
        for(String str : map.keySet()) {
            queue.offer(str);
        }
        for (int i = 0; i < k; i++) {
            list.add(queue.poll());
        }
        return list;
    }
}
